package com.ruoyi.ldzlsb.service.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Calendar;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.ruoyi.common.core.utils.DateUtils;
import com.ruoyi.common.core.utils.StringUtils;
import com.ruoyi.common.security.utils.SecurityUtils;
import com.ruoyi.ldzlsb.domain.SbInspectionDateRecord;
import com.ruoyi.ldzlsb.domain.SbInspectionCycleConfig;
import com.ruoyi.ldzlsb.domain.SbInspectionPlan;
import com.ruoyi.ldzlsb.domain.SbInspectionRecord;
import com.ruoyi.ldzlsb.mapper.SbInspectionDateRecordMapper;
import com.ruoyi.ldzlsb.mapper.SbInspectionCycleConfigMapper;
import com.ruoyi.ldzlsb.mapper.SbInspectionPlanMapper;
import com.ruoyi.ldzlsb.service.ISbInspectionDateRecordService;
import com.ruoyi.ldzlsb.util.InspectionDateCalculator;

/**
 * 巡检日期记录Service业务层处理
 * 
 * @author ruoyi
 */
@Service
public class SbInspectionDateRecordServiceImpl implements ISbInspectionDateRecordService 
{
    private static final Logger logger = LoggerFactory.getLogger(SbInspectionDateRecordServiceImpl.class);
    
    @Autowired
    private SbInspectionDateRecordMapper sbInspectionDateRecordMapper;
    
    @Autowired
    private SbInspectionCycleConfigMapper sbInspectionCycleConfigMapper;
    
    @Autowired
    private SbInspectionPlanMapper sbInspectionPlanMapper;

    /**
     * 查询巡检日期记录
     * 
     * @param recordId 巡检日期记录主键
     * @return 巡检日期记录
     */
    @Override
    public SbInspectionDateRecord selectSbInspectionDateRecordByRecordId(Long recordId)
    {
        return sbInspectionDateRecordMapper.selectSbInspectionDateRecordByRecordId(recordId);
    }

    /**
     * 查询巡检日期记录列表
     * 
     * @param sbInspectionDateRecord 巡检日期记录
     * @return 巡检日期记录
     */
    @Override
    public List<SbInspectionDateRecord> selectSbInspectionDateRecordList(SbInspectionDateRecord sbInspectionDateRecord)
    {
        return sbInspectionDateRecordMapper.selectSbInspectionDateRecordList(sbInspectionDateRecord);
    }

    /**
     * 新增巡检日期记录
     * 
     * @param sbInspectionDateRecord 巡检日期记录
     * @return 结果
     */
    @Override
    public int insertSbInspectionDateRecord(SbInspectionDateRecord sbInspectionDateRecord)
    {
        sbInspectionDateRecord.setCreateTime(DateUtils.getNowDate());
        sbInspectionDateRecord.setCreateBy(SecurityUtils.getUsername());
        return sbInspectionDateRecordMapper.insertSbInspectionDateRecord(sbInspectionDateRecord);
    }

    /**
     * 修改巡检日期记录
     * 
     * @param sbInspectionDateRecord 巡检日期记录
     * @return 结果
     */
    @Override
    public int updateSbInspectionDateRecord(SbInspectionDateRecord sbInspectionDateRecord)
    {
        sbInspectionDateRecord.setUpdateTime(DateUtils.getNowDate());
        sbInspectionDateRecord.setUpdateBy(SecurityUtils.getUsername());
        return sbInspectionDateRecordMapper.updateSbInspectionDateRecord(sbInspectionDateRecord);
    }

    /**
     * 批量删除巡检日期记录
     * 
     * @param recordIds 需要删除的巡检日期记录主键
     * @return 结果
     */
    @Override
    public int deleteSbInspectionDateRecordByRecordIds(Long[] recordIds)
    {
        return sbInspectionDateRecordMapper.deleteSbInspectionDateRecordByRecordIds(recordIds);
    }

    /**
     * 删除巡检日期记录信息
     * 
     * @param recordId 巡检日期记录主键
     * @return 结果
     */
    @Override
    public int deleteSbInspectionDateRecordByRecordId(Long recordId)
    {
        return sbInspectionDateRecordMapper.deleteSbInspectionDateRecordByRecordId(recordId);
    }

    /**
     * 根据巡检单ID查询巡检日期记录列表
     * 
     * @param inspectionRecordId 巡检单ID
     * @return 巡检日期记录集合
     */
    @Override
    public List<SbInspectionDateRecord> selectSbInspectionDateRecordByInspectionRecordId(Long inspectionRecordId)
    {
        return sbInspectionDateRecordMapper.selectSbInspectionDateRecordByInspectionRecordId(inspectionRecordId);
    }

    /**
     * 根据巡检单和日期查询巡检日期记录
     * 
     * @param inspectionRecordId 巡检单ID
     * @param inspectionDate 巡检日期
     * @return 巡检日期记录
     */
    @Override
    public SbInspectionDateRecord selectSbInspectionDateRecordByDate(Long inspectionRecordId, Date inspectionDate)
    {
        SbInspectionDateRecord query = new SbInspectionDateRecord();
        query.setInspectionRecordId(inspectionRecordId);
        query.setInspectionDate(inspectionDate);
        List<SbInspectionDateRecord> list = sbInspectionDateRecordMapper.selectSbInspectionDateRecordList(query);
        return list.size() > 0 ? list.get(0) : null;
    }

    /**
     * 批量保存巡检日期记录
     * 
     * @param recordList 巡检日期记录列表
     * @return 结果
     */
    @Override
    @Transactional
    public int batchSaveSbInspectionDateRecord(List<SbInspectionDateRecord> recordList)
    {
        if (recordList == null || recordList.isEmpty()) {
            return 0;
        }
        
        for (SbInspectionDateRecord record : recordList) {
            record.setCreateTime(DateUtils.getNowDate());
            record.setCreateBy(SecurityUtils.getUsername());
            record.setUpdateTime(DateUtils.getNowDate());
            record.setUpdateBy(SecurityUtils.getUsername());
        }
        
        return sbInspectionDateRecordMapper.batchInsertSbInspectionDateRecord(recordList);
    }
    
    /**
     * 初始化巡检单的巡检日期记录
     * 
     * @param record 巡检单
     * @return 巡检日期记录列表
     */
    @Override
    @Transactional
    public List<SbInspectionDateRecord> initInspectionDateRecords(SbInspectionRecord record)
    {
        List<SbInspectionDateRecord> dateRecords = new ArrayList<>();
        
        // 获取巡检计划
        if (record.getPlanId() == null) {
            logger.error("巡检单没有关联的巡检计划，无法初始化巡检日期记录");
            return dateRecords;
        }
        
        SbInspectionPlan plan = sbInspectionPlanMapper.selectSbInspectionPlanByPlanId(record.getPlanId());
        if (plan == null) {
            logger.error("找不到关联的巡检计划，planId={}", record.getPlanId());
            return dateRecords;
        }
        
        // 获取周期配置
        SbInspectionCycleConfig cycleConfig = sbInspectionCycleConfigMapper.selectSbInspectionCycleConfigByPlanId(plan.getPlanId());
        if (cycleConfig == null) {
            logger.error("找不到巡检计划的周期配置，planId={}", plan.getPlanId());
            return dateRecords;
        }
        
        // 计算巡检日期
        List<Date> inspectionDates = calculateInspectionDates(plan, cycleConfig);
        
        // 创建日期记录
        for (Date date : inspectionDates) {
            SbInspectionDateRecord dateRecord = new SbInspectionDateRecord();
            dateRecord.setInspectionRecordId(record.getRecordId());
            dateRecord.setInspectionDate(date);
            dateRecord.setStatus("0");  // 初始状态：未巡检
            dateRecord.setCreateTime(DateUtils.getNowDate());
            dateRecord.setCreateBy(SecurityUtils.getUsername());
            dateRecords.add(dateRecord);
        }
        
        // 批量插入
        if (!dateRecords.isEmpty()) {
            sbInspectionDateRecordMapper.batchInsertSbInspectionDateRecord(dateRecords);
        }
        
        return dateRecords;
    }
    
    /**
     * 检查巡检单是否已完成所有日期的巡检
     * 
     * @param inspectionRecordId 巡检单ID
     * @return 是否完成
     */
    @Override
    public boolean checkAllDatesCompleted(Long inspectionRecordId)
    {
        List<SbInspectionDateRecord> records = selectSbInspectionDateRecordByInspectionRecordId(inspectionRecordId);
        if (records.isEmpty()) {
            return false;
        }
        
        for (SbInspectionDateRecord record : records) {
            if (!"1".equals(record.getStatus())) {
                // 有未完成的日期
                return false;
            }
        }
        
        return true;
    }
    
    /**
     * 根据巡检单ID更新所有日期记录的状态
     * 
     * @param inspectionRecordId 巡检单ID
     * @param status 状态
     * @return 结果
     */
    @Override
    @Transactional
    public int updateStatusByInspectionRecordId(Long inspectionRecordId, String status)
    {
        List<SbInspectionDateRecord> records = selectSbInspectionDateRecordByInspectionRecordId(inspectionRecordId);
        int count = 0;
        
        for (SbInspectionDateRecord record : records) {
            record.setStatus(status);
            record.setUpdateTime(DateUtils.getNowDate());
            record.setUpdateBy(SecurityUtils.getUsername());
            count += updateSbInspectionDateRecord(record);
        }
        
        return count;
    }
    
    /**
     * 根据计划和周期配置计算巡检日期列表
     * 
     * @param plan 巡检计划
     * @param cycleConfig 周期配置
     * @return 巡检日期列表
     */
    private List<Date> calculateInspectionDates(SbInspectionPlan plan, SbInspectionCycleConfig cycleConfig)
    {
        // 使用日期计算工具类计算巡检日期
        return InspectionDateCalculator.calculateInspectionDates(plan, cycleConfig);
    }
} 